<template>
  <div>
    <h1>Axios发送http请求</h1>
    <p>
      Axios 是一个基于 promise 网络请求库，作用于node.js 和浏览器中。 发送http请求
    </p>
    <hr>
    <el-button type="primary" plain @click="getMethod">GET</el-button>
    <el-button type="primary" plain @click="getMethod2">GET params</el-button>
    <el-button type="primary" plain @click="postMethod">POST</el-button>
    <el-button type="primary" plain @click="postMethod2">POST params</el-button>

    <hr>
    <el-button type="primary" plain @click="instanceGetMethod"> axios instance GET</el-button>
    <el-button type="primary" plain @click="login"> login</el-button>
    <el-button type="primary" plain @click="register"> register</el-button>


  </div>
</template>

<script>
import axios from "axios";
import instance from "@/utils/request";
import {login,register} from '@/api/user'
export default {
  name: "AxiosView",
  methods: {
    login(){
        login({name:'tom',age:20}).then((res)=>{
          console.log(res)
        })
    },
    register(){
      register({name:'tom',age:20}).then((res)=>{
        console.log(res)
      })
    },
    getMethod() {
      // form   http  后台接口  get  Promise  .then 成功      .catch  失败     .finally  总要执行
      axios.get('http://192.168.253.159:8000/user/delete')
          .then(function (response) {
            console.log(response)
            // 处理成功情况
            this.$message.success('请求成功')
          })
          .catch(function (error) {
            console.log(error)
            // 处理错误情况
            this.$message.error('请求成功')
          })
          .finally(function () {
            // 总是会执行
            this.$message.error('finally总要执行')
          });
    },
    getMethod2() {
      axios({
        method: 'get',
        // url: 'http://bit.ly/2mTM3nY?id=1',
        url: 'http://bit.ly/2mTM3nY',
        params: {
          id: 12345,
          name: "tom"
        }
      }).then(function (response) {
        console.log('请求成功', response)
      });
    },
    postMethod() {
      /*
      * http  code
      *   2xx  成功
      *   3xx  重定向
      *   4xx  前端错误   404  url  401 没有认证  403 没有权限
      *   5xx  500    后台服务器错误
      * */
      this.$message.info('post请求')
      axios.post('/user')
          .then(function (response) {
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });
    },
    postMethod2() {
      axios.post('http://192.168.253.159:8000/user', {id: '123456', name: 'jack'}).then(function (response) {
        console.log('请求成功', response)
      });
    },
    instanceGetMethod() {
      //  http://192.168.253.159:8000/user
      instance.get('/user').then(function (response) {
        console.log(response)
      }).catch(function (error) {
        console.log(error)
      })
    }
  }
}
</script>

<style scoped>

</style>
